<?php
use Sts\Request\V20150401 as Sts;
include "./include/function.inc.php";


    function is_login_cc($token=''){
        $model = M('token');
        $uid =$model->where(['token'=>$token])->getField('aId'); 
        if($uid)$user = get_user_basecc($uid);
        return $user;
    }

    function is_login_cctt($token=''){
        $model = M('user_token');
        $uid =$model->where(['token'=>$token])->getField('uids'); 
        if($uid)$user = get_user_basecc($uid);
        return $user;
    }

/**
 * 检测用户是否登录
 * @param $msg      关键字
 * @param $login    登录方式 web,app,
 * @param $token    验证串
 * @return int 0-未登录，大于0-当前登录用户ID
 */
function is_login($msg='user_msg', $login='web', $token=''){
    //数据库验证方式
    C('USER_CHECK_MODEL','db');//直接用db
    if($token && strtolower(C('USER_CHECK_MODEL'))){//token 存在且开启认证模式
        if(strtolower(C('USER_CHECK_MODEL'))=='db'){
            $ut_model = D('Token');
            $result = $ut_model->checkToken($token);
            if($result['status']==1){
                $user = $result['data'];
            }
        }else if(strtolower(C('USER_CHECK_MODEL'))=='redis'){
            //获取用户信息
            //redis存储
            $str = authcode($token);
            $n = strpos($str, '_');
            $uid = substr($str,0,$n);
            $redis = new \Redis();
            $config = C('APP_TOKEN_CONFIG');
            $redis->connect($config['host'], $config['port']);
            $redis->auth($config['password']);
            $e_uid = $redis->get('WToken_'.$uid);
            $uid = authcode($e_uid);
            if($uid)$user = get_user_base($uid);
        }
    }else{
        //WEB:验证方式
        if(strtolower(C('USER_CHECK_MODEL'))=='cookie'){
            //dump(authcode(cookie($msg)));exit;
            $user = unserialize(authcode(cookie($msg)));
        }else{
            $user = unserialize(authcode(session($msg)));
        }
        //dump($user);
    }
    if (empty($user)) {
        return '';
    } else {
        return $user;
    }
}

//获取客户基本信息
function get_user_basecc($uid){
	$model = D('User');
    $wdata['uid'] = $uid;
	$user_msg = $model->where($wdata)->find();
    return $user_msg;
}

//获取用户基本信息
function get_user_base($aId){
	$model = D('Admin');
    $wdata['aId'] = $aId;
	$user_msg = $model->where($wdata)->find();
    return $user_msg;
}

//根据id获得路径
/*
 *  $id
 *  $len 7位每个ID独立目录 9位 1-99使用同一个目录
 */
function get_dir($id ,$len = 7) {
    //$size = in_array($size, array('b', 'm', 's')) ? $size : 'm';
	$id = abs(intval($id));
	$id = sprintf("%0".$len."d", $id);
	$dir1 = substr($id, 0, 3);
	$dir2 = substr($id, 3, 2);
	if($len==9)$dir3 = substr($id, 5, 2);
    if($len==7){
        return $dir1.'/'.$dir2.'/'.substr($id, -2);
    }else{
        return $dir1.'/'.$dir2.'/'.$dir3;
    }
    
}

/**
 * 设置跳转页面URL
 * 使用函数再次封装，方便以后选择不同的存储方式（目前使用cookie存储）
 */
function set_redirect_url($url=__SELF__){
    if(!IS_AJAX && !IS_POST){
        cookie('redirect_url', $url);
    }
}

/**
 * 获取跳转页面URL
 * @return string 跳转页URL
 */
function get_redirect_url(){
    //if(!IS_AJAX){
        $url = cookie('redirect_url');
        return empty($url) ? __ROOT__ : $url;
    //}
}

/**
 * 上传图片
 * $options 
 */
function imageupload_v5($options = array()){
    $config['maxSize'] = 1024*1024*(C('upload_size') ? : 2);
    $config['exts'] = array('jfif','jpg','jpeg','gif','png','swf','xls','txt');
    $config['saveRule'] = 'uniqid';
    $config['rootPath'] = './'.C('Wup').'/';
    $config['savePath'] = '';
    //$config['subName'] = date('Y/m/d');
    $config['subName'] = array('date', 'Y/m/d');
    $config['driver'] = C('FILE_UPLOAD_TYPE') ? C('FILE_UPLOAD_TYPE') : 'Local';
    $config['thumb'] = C('thumb');
    $config['thumbPrefix'] = C('thumbPrefix');  //生产2张缩略图
    $config['thumbMaxWidth'] = C('thumbMaxWidth');
    $config['thumbMaxHeight'] = C('thumbMaxHeight');
    if($options){
        $config = array_merge($config,$options);
    }
    $upload = new \Think\Upload($config);
    $info = $upload->upload();
    if($info){
		foreach($info as $file){
			$key = $file['key'];
			//$_POST[$key] = C('Wimgurl').'/'.$file['savepath'].$file['savename'];//存绝对路径
			$_POST[$key] = $file['savepath'].$file['savename'];//存相对路径
			$result['filepath'][$key] = $file['savepath'].$file['savename'];//存相对路径
			$result['url'][$key] = C('Wimgurl').'/'.$file['savepath'].$file['savename'];//绝对路径
		}
		$result['status'] = 1;
		$result['data'] = $info;
    }else{
		$result['status'] = 0;
		$result['error'] = $upload->getError();
    }
    return $result;
}

//判断内网ip
function check_ip($ip){
    if($ip=='::1' || $ip=='127.0.0.1' || $ip=='0.0.0.0'){
        return true;
    }
    $ip = ip2long($ip);
    $net_a = ip2long('10.255.255.255') >> 24; //A类网预留ip的网络地址
    $net_b = ip2long('172.31.255.255') >> 20; //B类网预留ip的网络地址
    $net_c = ip2long('192.168.255.255') >> 16; //C类网预留ip的网络地址
    return $ip >> 24 === $net_a || $ip >> 20 === $net_b || $ip >> 16 === $net_c;
}
  
/**
 * 获得缩略图
 * @param $url  图片链接地址
 * @param $size 尺寸(w_100 宽100px,w_100,h_120 宽100px高120px) 已阿里云为标准
 * @return mixed
 */
function get_thumb($url,$size){
    if(C('UP_DRIVER')=='AliOss'){
        //https://help.aliyun.com/document_detail/44688.html?spm=a2c4g.11186623.6.1402.cf2a220dzaP5Zi
        $return_url = $url.'?x-oss-process=image/resize,'.$size.',limit_0';
    }else if(C('UP_DRIVER')=='TenCos'){
        //https://cloud.tencent.com/document/product/460/6929
        $tx_size = str_ireplace("_", "/", $size);
        $tx_size = str_ireplace(",", "/", $tx_size);
        $return_url = $url.'?imageView2/2/'.$tx_size;
    }else{
        if(preg_match('/\d+/',$size,$arr)){
            $number = $arr[0];
        }
        $basename = basename($url);
        $return_url = str_replace($basename,$number.'_'.$basename,$url);
        $dir = C('Wup').str_replace(C('Wimgurl'),'',$return_url);
        if(file_exists($dir)===false){
            //本地文件不存在
            $return_url = $url.'" width="'.$number.'px;"';
        }
        
    }
    return $return_url;
}

/**
 * 更新财务资金记录
 * $data['val']：必填，更新的值，如：$data['val']=100;
 * $data['type']：必填，修改资金的类型
 * $data['remark']:非必填，修改资金的备注
 * 返回：数组,status(1成功 0错误) msg(错误的时候输出信息，成功的时候输出SQL语句)
 */
function userMoneyUpdate($data){
    $return = [
        'status' => false,
        'errcode'   => 10000,
        'data'   => '',
        'msg'    => '失败'
    ];
    $money_finance_type = getUtype($data['f_type']);//获取财务更新项
    if(!empty($money_finance_type)){
        //财务数据
        $u_model = M('User');
        $u_wdata['uid'] = $data['uid'];
        $u_vo = $u_model->where($u_wdata)->lock(true)->find();//锁行
        if($data['type'] == 2 && $u_vo['amount']<$data['val']){
            $return['msg'] = '用户余额不足 - u1000';
            return $return;
        }
        if($data['type'] == 1){
            //收入
            $f_data['amount'] = array('exp',"amount+{$data[val]}");
        }elseif($data['type'] == 2){
            //支出
            $f_data['amount'] = array('exp',"amount-{$data[val]}");
        }else{
            $return['msg'] = '类型错误 - u1000';
            return $return;            
        }
        $result = $u_model->where($u_wdata)->save($f_data);
        if(!$result){
            //return array('status'=>0,'msg'=>M()->_sql());
            $return['msg'] = '更新数据错误 - u1001';
            return $return;  
        }else{
            $sqls[] = M()->_sql();
        }
        $u_vo = $u_model->where($u_wdata)->find();
        //财务数据历史
        $fh_model = M('UserMoneyHistory');
        $fh_data['name'] = substr($money_finance_type, 0,1);
        $fh_data['uid'] = $data['uid'] ? : 0;
        $fh_data['change_val'] = $data['val'];
        $fh_data['amount'] = $u_vo['amount'];//更新后金额
        $fh_data['type'] = $data['type'];
        $fh_data['f_type'] = $data['f_type'];
        $fh_data['aid'] = defined('UID') ? UID:0;
        $fh_data['pay_time'] = $data['pay_time'] ? : NOW_TIME;
        $fh_data['add_time'] = NOW_TIME;
        $fh_data['remark'] = $data['remark'];
        $fh_data['source'] = $data['source'] ? : '';
        $fh_data['source_id'] = $data['source_id'] ? : 0;
        $fh_id = $fh_model->add($fh_data);
        if(!$fh_id){
            return array('status'=>0,'msg'=>M()->_sql());
        }else{
            $sqls[] = M()->_sql();
        }
		$return['status'] = 1;
		$return['data'] = $fh_id;//历史记录ID
    }else{
		$return['status'] = 0;
		$return['msg'] = '无效的类型';
        return $return;
	}
    $return['sqls'] = $sqls;
    $return['status'] = true;
    $return['msg'] = '操作成功';
    return $return;
}

/*
根据资金变动类型获取状态、用户自动更新财务信息 
status  0或无 帐内交易 c1公司账户收入 c-1公司账户支出
*/
function u_type(){
    $array = array(
        101=>'充值',
        102=>'订单',
        //其他
        999=>'其他',
    );
    return $array;
}

//获取类型名称
function getUtype($type){
    $array = u_type();
   return $array[$type];
}

/**
 * 更新财务资金记录
 * $data['val']：必填，更新的值，如：$data['val']=100;
 * $data['type']：必填，修改资金的类型
 * $data['remark']:非必填，修改资金的备注
 * 返回：数组,status(1成功 0错误) msg(错误的时候输出信息，成功的时候输出SQL语句)
 */
function fund($data){
    $return = [
        'status' => false,
        'errcode'   => 10000,
        'data'   => '',
        'msg'    => '失败'
    ];
    $money_finance_type = getFtype($data['f_type']);//获取财务更新项
    if(!empty($money_finance_type)){
        //财务数据
        $f_model = M('Finance');
        if(!$f_model->where('id=1')->getfield('id')){
            $f_model->add(array('id'=>1));
        }
        $f_data['id'] = 1;
        if($data['type'] == 1){//公司收入
            $f_data['amount'] = array('exp',"amount+{$data[val]}");
            $f_data['receive_amount'] = array('exp',"receive_amount+{$data[val]}");
        }elseif($data['type'] == 2){//公司支出
            $f_data['amount'] = array('exp',"amount-{$data[val]}");
            $f_data['pay_amount'] = array('exp',"pay_amount+{$data[val]}");
        }else{
            $return['msg'] = '类型错误 - c1000';
            return $return;            
        }
        $result = $f_model->save($f_data);
        if(!$result){
            //return array('status'=>0,'msg'=>M()->_sql());
            $return['msg'] = '更新数据错误 - c1001';
            return $return;  
        }else{
            $sqls[] = M()->_sql();
        }
        $f_vo = $f_model->find();
        //财务数据历史
        $fh_model = M('FinanceHistory');
        $fh_data['name'] = substr($money_finance_type, 0,1);
        $fh_data['uid'] = $data['uid'] ? : 0;
        $fh_data['suppliers_id'] = $data['suppliers_id'] ? : 0;
        $fh_data['change_val'] = $data['val'];
        $fh_data['amount'] = $f_vo['amount'];//更新后金额
        $fh_data['type'] = $data['type'];
        $fh_data['f_type'] = $data['f_type'];
        $fh_data['aid'] = defined('UID') ? UID : 0;
        $fh_data['pay_time'] = $data['pay_time'] ? : NOW_TIME;
        $fh_data['add_time'] = NOW_TIME;
        $fh_data['remark'] = $data['remark'];
        $fh_data['source'] = $data['source'] ? : '';
        $fh_data['source_id'] = $data['source_id'] ? : 0;
        $fh_id = $fh_model->add($fh_data);
        if(!$fh_id){
            return array('status'=>0,'msg'=>M()->_sql());
        }else{
            $sqls[] = M()->_sql();
        }
		$return['status'] = 1;
		$return['data'] = $fh_id;//历史记录ID
    }else{
		$return['status'] = 0;
		$return['msg'] = '无效的类型';
        return $return;
	}
    $return['sqls'] = $sqls;
    $return['status'] = true;
    $return['msg'] = '操作成功';
    return $return;
}

/*
根据资金变动类型获取状态、用户自动更新财务信息 
*/
function finance_type(){
    $array = array(
        101=>'采购',
        102=>'订单',
        301=>'充值',
        //其他
        999=>'其他',
    );
    return $array;
}

//获取类型名称
function getFtype($type){
    $array = finance_type();
   return $array[$type];
}

//获得缩略图
function oss_get_thumb($url,$size){
   $ar = explode(',',$size);
   $w = $ar[0];
   $h = $ar[1] ? $ar[1] : $w;
   $url = $url."?x-oss-process=image/resize,w_{$w},h_{$h}/auto-orient,1/quality,q_90/format,jpg";
   return $url;
}

// 循环创建目录
function mk_dir($dir, $mode = 0775) {

    if (is_dir($dir) || @mkdir($dir, $mode)){
		if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')@chmod($dir,$mode);
        return true;
	}
    if (!mk_dir(dirname($dir), $mode)){
        return false;
	}
	$result = @mkdir($dir, $mode);
	if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')@chmod($dir,$mode);
    return $result;
}

/**
中间星号代替
*/
function cut_str($string,$leng=2,$num=0){
    $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
    preg_match_all($pa, $string, $t_string);
    $count=count($t_string[0]);
    if($count==2){$jqz=1;$i_count=2;}elseif($count>4){$jqz=$leng;$i_count=$count-$jqz-1;}else{$jqz=1;$i_count=$count-$jqz;}
    $v1=join('', array_slice($t_string[0],0,$jqz));//明文前
    if($count!=2){
        $v2=join('', array_slice($t_string[0],-$jqz));//明文后
    }
    if($num>0){
      $i_count = $num+1;
    }

    for($i=1;$i<$i_count;$i++){
        $v3.='*';
    }
    return $v1.$v3.$v2;exit;
    
}


/**
UTF-8字符串截取函数
str 字符串
length 字符串长度
return 截取后的字符串
*/
function ngg_substr($str, $length) {
    $carr = subString_UTF8($str, 0, $length);
    $cstr = implode('', $carr);
    if (utf8_strlen($cstr) < utf8_strlen($str)) {
        $cstr .= '...';
    }
    return $cstr;
}

function subString_UTF8($str, $start, $lenth) {
    $len = strlen($str);
    $r = array();
    $n = 0;
    $m = 0;
    for ($i = 0; $i < $len; $i++) {
        $x = substr($str, $i, 1);
        $a = base_convert(ord($x), 10, 2);
        $a = substr('00000000' . $a, -8);
        if ($n < $start) {
            if (substr($a, 0, 1) == 0) {
                
            } elseif (substr($a, 0, 3) == 110) {
                $i += 1;
            } elseif (substr($a, 0, 4) == 1110) {
                $i += 2;
            }
            $n++;
        } else {
            if (substr($a, 0, 1) == 0) {
                $r[] = substr($str, $i, 1);
            } elseif (substr($a, 0, 3) == 110) {
                $r[] = substr($str, $i, 2);
                $i += 1;
            } elseif (substr($a, 0, 4) == 1110) {
                $r[] = substr($str, $i, 3);
                $i += 2;
            } else {
                $r[] = '';
            }
            if (++$m >= $lenth) {
                break;
            }
        }
    }
    return $r;
}

function utf8_strlen($str) {
    $count = 0;
    for ($i = 0; $i < strlen($str); $i++) {
        $value = ord($str[$i]);
        if ($value > 127) {
            $count++;
            if ($value >= 192 && $value <= 223)
                $i++;
            elseif ($value >= 224 && $value <= 239)
                $i = $i + 2;
            elseif ($value >= 240 && $value <= 247)
                $i = $i + 3;
            else
                die('Not a UTF-8 compatible string');
        }
        $count++;
    }
    return $count;
}

/**
 *  过滤
 *  @param  $content 内容
 *  @param  $type    1: 超链接过滤 2:js过滤 3:都过滤
 *  @return string
 */
function filter($content, $type=3){
  if($type==3){
    //去外链
    $content = trim($content);
    $content = preg_replace("/<a.*?>(.*?)<\/a>/is", "\$1",$content);
    $content = preg_replace("/&lt;a.*?&gt;(.*?)&lt;\/a&gt;/is", "\$1",$content);
    //去JS
    $content = preg_replace("/<script.*?<\/script>/is", "",$content);
    $content = preg_replace("/&lt;script.*?&lt;\/script&gt;/is", "",$content);
    $content = preg_replace("/((class|onerror|onload|onclick)=\".*?\")/is", "",$content);  
  }else if($type==1){
    //去外链
    $content = trim($content);
    $content = preg_replace("/<a.*?>(.*?)<\/a>/is", "\$1",$content);
    $content = preg_replace("/&lt;a.*?&gt;(.*?)&lt;\/a&gt;/is", "\$1",$content);  
  }else{
    //去JS
    $content = preg_replace("/<script.*?<\/script>/is", "",$content);
    $content = preg_replace("/&lt;script.*?&lt;\/script&gt;/is", "",$content);
    $content = preg_replace("/((class|onerror|onload|onclick)=\".*?\")/is", "",$content);  
  }
  return $content;
}

/**
 * 返回一个20位的随机数
 * @param  integer $id [用户ID，默认为0]
 * @return [type]      [和用户ID相关的20位的随机数]
 */
function get_rand_num($id=0){
    $num  = date('Ymd').$id.mt_rand(0,9999);
    $length = 20 - strlen($num); // 只存在数字,不存在多字符
    $pattern='1234567890';
    for ($i=0;$i<$length;$i++) { 
        $num .= $pattern[mt_rand(0,9)];
    }
    return $num ;
}

//加密解密
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    
    if($operation == 'DECODE') {
        $string = str_replace('[x]','+',$string);
        $string = str_replace('[p]','&',$string);
        $string = str_replace('[w]','/',$string);   
    } 

	$ckey_length = 3;	//note 随机密钥长度 取值 0-32;
				//note 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
				//note 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
				//note 当此值为 0 时，则不产生随机密钥

	$key = md5($key ? $key : C('SysUserAuth'));
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);
	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + NOW_TIME : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - NOW_TIME > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		//return $keyc.str_replace('=', '', base64_encode($result));
        $ustr = $keyc.str_replace('=', '', base64_encode($result));
        $ustr = str_replace('+','[x]',$ustr);
        $ustr = str_replace('&','[p]',$ustr);
        $ustr = str_replace('/','[w]',$ustr);
        return $ustr; 
	}
}

//时间戳转换
function toDate($time,$format='Y-m-d H:i:s') {
	if( empty($time)) {
		return '--';
	}
    $format = str_replace('#',':',$format);
	return date($format,$time);
}

//解决uniqid 并发
function uniqid_pd($val=''){
    $uniqid = uniqid();
    if($uniqid == $val){
        return uniqid_pd($val);
    }
    return $uniqid;
}

/**
 +----------------------------------------------------------
 * 生成唯一编码
 +----------------------------------------------------------
 * @param string $type 字串类型
 * 0 混合 1 数字
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function get_code($type=0){
    if($type==0){
        $uniqid = uniqid();
        $rand = rand_string(4,4);//随机数
        $code = substr($uniqid,0,4).'-'.substr($uniqid,4,4).'-'.substr($uniqid,8,5).'-'.$rand;
    }else{
        $work = new \Think\IdWork(1,1);
        $code = $work->nextId();//可用于uid
    }
    return $code;
}

/**
 * 下划线转驼峰
 * 思路:
 * step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
 * step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
 */
function camelize($uncamelized_words, $type=1){
	if($type==0){
		$uncamelized_words = '_'. str_replace('_', " ", strtolower($uncamelized_words));
	}else{
		$uncamelized_words = str_replace('_', " ", strtolower($uncamelized_words));
	}
	return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), '_' );
}

/**
 * 驼峰命名转下划线命名
 * 思路:
 * 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
 */
function uncamelize($camelCaps,$separator='_'){
	return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
}

//生成订单号
function build_order_no($prefix = 'XS'){
	$his = time();
	//$msec = mt_rand(10000,99999);
    $msec = '';
    for($i=0;$i<5;$i++){
        $msec .= mt_rand(0,9);
    }
    //$str = substr($his,0,2).substr($msec,0,2).substr($msec,2,1).substr($his,2,2).substr($msec,3,2).substr($his,4,1);
	$str = $his.$msec;
	$orderSn = $prefix. $str;
	return $orderSn;
}

/**
 +----------------------------------------------------------
 * 二维码生成
 +----------------------------------------------------------
 * @param string $ewm_file_pic 二维码保存路径
 * @param string $url 跳转url
 * @param array  $option 二维码参数 
 * level:容错级别; size:生成图片大小; margin:空白区域大小; ewm_width:固定大小
 +----------------------------------------------------------
 * @return array
 +----------------------------------------------------------
 */
function createQrcode($ewm_file_pic, $url, $option = array()){
    $return = [
        'status' => true,
        'msg'    => '生成成功',
        'data'   => []
    ];
    if(!$ewm_file_pic){
        $return['status'] = false;
        $return['msg'] = '保存地址必须';
        return $return;
    }
    if(!$url){
        $return['status'] = false;
        $return['msg'] = '跳转地址必须';
        return $return;    
    }
    //PHP生成图片
    include ROOT_PATH."include/phpqrcode.php";
    $Qcode = new \QRcode();
    //容错率 L(QR_ECLEVEL_L，7%)、M(QR_ECLEVEL_M，15%)、Q(QR_ECLEVEL_Q，25%)、H(QR_ECLEVEL_H，30%)
    //$size：控制生成图片的大小，默认为4； 1-29px,2-58px,6-174px 每级+29px;
    $level = $option['level'] ? : 'L';	//容错级别 
    $size = $option['size'] ? : 6;		//生成图片大小 
    $margin = $option['margin'] ? : 2;    //控制生成二维码的空白区域大小；每级+12px;
    $ewm_width = $option['ewm_width'] ? : ''; //logo固定大小
    $Qcode->png($url,$ewm_file_pic,$level,$size,$margin,true);
    $image = new \Think\Image();
    //二维码加logo
    if($option['add_logo']){
        //准备好的logo图片
        $logo = C('Wlogo');
        //$logo = 'https://jy07.oss-cn-shenzhen.aliyuncs.com/avatar/000/00/04/6243fabf85230.jpg';
        $logo_info = get_path($logo);
        if(!$logo_info['status']){
            $return['status'] = false;
            $return['msg'] = 'logo获取失败';
            return $return;    
        }
        $logo_path = $logo_info['data'];
        if($logo_info['is_temp']){
            $del_logo = $logo_info['data'];
        }
        //获取物理路径
        //临时文件夹
        $temp_path = C('Wup').'/temp/';
        mk_dir($temp_path);
        $logo_info2 = getimagesize($logo_path);
        if($logo_info2[0]>50 || $logo_info2[2]>50){
            //长宽大于100,压缩复制到临时文件夹
            $logo_temp_path = $temp_path.uniqid(true).'.jpg';
            $r = $image->open($logo_path)->thumb(50, 50)->save($logo_temp_path);
            $logo_path = $logo_temp_path;
        }
        $image->open($ewm_file_pic)->water($logo_path,\Think\Image::IMAGE_WATER_CENTER,95)->save($ewm_file_pic);
        if($logo_temp_path){
            unlink($logo_temp_path);
        }
        if($logo_info['is_temp']){
            unlink($del_logo);
        }
    }
    // 按照原图的比例生成一个最大为150*150的缩略图并覆盖
    if($ewm_width){
        $image->open($ewm_file_pic)->thumb($ewm_width, $ewm_width)->save($ewm_file_pic);
    }
    //上传到云端
    if(C('FILE_UPLOAD_TYPE')!='Local'){
        $upload = new \Think\Upload();
        $root = __ROOT__.C('Wup').'/';
        $to_file = str_ireplace($root, "", $ewm_file_pic);
        $result = $upload->direct($ewm_file_pic, $to_file);
        //删除本地
        unlink($ewm_file_pic);
    }
    return $return;
}


//导出
function excelDown($arr,$filename){
    $fileName = $filename;
    /*
    $xlsCell=array(
        array('index','序号'),
        array('name','姓名'),
        array('sno','学号'),
        array('gender','性别'),
        array('idcard','身份证号'),
        array('college','学院'),
        array('major','专业'),
        array('grade','年级'),
        array('classes','班级'),
        array('mobile','手机号码'),
        array('email','电子邮箱'),
        array('status','状态')
    );
    */
    $xlsCell = $arr['field'];
    $data = $arr['data'];
    exportExcel($fileName,$xlsCell,$data);
}

function exportExcel($fileName,$expCellName,$expTableData){
    $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
    //$fileName = date('YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
    $cellNum = count($expCellName);//字段数量
    $dataNum = count($expTableData);
    vendor("Excel.PHPExcel");
    set_time_limit(600);      //执行时间无限
    ini_set('memory_limit','512M');    //-1内存无限
    $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_to_apc;
    $cacheSettings = array('cacheTime'  => 600);
    \PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
    $objPHPExcel = new \PHPExcel();
    $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV');
    $cell=$objPHPExcel->getActiveSheet(0);
    for($i=0;$i<$cellNum;$i++){
        $cell->setCellValue($cellName[$i].'1', $expCellName[$i]);
        $cell->getStyle($cellName[$i].'1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $cell->getStyle($cellName[$i].'1')->getFont()->setBold(true);
    }
    //设置值
    foreach($expTableData as $key=>$val){
         for($k=0;$k<$cellNum;$k++){
             $cell->setCellValue($cellName[$k].($key+2),$val[$k]);
         }
    }
    //exit;
    ob_clean();//清除缓冲区,避免乱码：
    header('pragma:public');
    header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xlsx"');
    header("Content-Disposition:attachment;filename=$fileName.xlsx");//attachment新窗口打印inline本窗口打印
    flush();
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('php://output');
    exit;
}

//导入处理
function importExcel($filepath){
    vendor("Excel.PHPExcel");
    set_time_limit(600);
    ini_set("memory_limit", "1024M");
    $file_type = \PHPExcel_IOFactory::identify($filepath);
    $objPHPExcel = \PHPExcel_IOFactory::load($filepath);
    $sheet = $objPHPExcel->getSheet(0);
    $data = $sheet->toArray();
    return $data;
}
//团体定制模板
function tuan_exportExcel($expTitle,$expCellName,$expTableData){
    $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
    $cellNum = count($expCellName);
    vendor("Excel.PHPExcel");
    set_time_limit(600);      //执行时间无限
    ini_set('memory_limit','512M');    //-1内存无限
    $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_to_apc;
    $cacheSettings = array('cacheTime'  => 600);
    \PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
    $objPHPExcel = new \PHPExcel();
    $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y');
    $cell=$objPHPExcel->getActiveSheet(0);

    $cell->mergeCells('A1:G1');//合并单元格
    $cell->mergeCells('H1:R1');//合并单元格
    $cell->mergeCells('S1:Y1');//合并单元格
    for ($i=0;$i<count($cellName);$i++){
        $objPHPExcel->getActiveSheet()->getColumnDimension($cellName[$i])->setWidth(20);
        for($j=1; $j<3;$j++){
            $cell->getStyle($cellName[$i].$j)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $cell->getStyle($cellName[$i].$j)->getBorders()->getLeft()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $cell->getStyle($cellName[$i].$j)->getBorders()->getTop()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $cell->getStyle($cellName[$i].$j)->getBorders()->getBottom()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $cell->getStyle($cellName[$i].$j)->getBorders()->getRight()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
        }
    }
    //表格样式
    $cell->getStyle('A1')->getFont()->setBold(true);//加粗
    $cell->getStyle('H1')->getFont()->setBold(true);//加粗
    $cell->getStyle('S1')->getFont()->setBold(true);//加粗
    $cell->setCellValue('A1','顾客信息');
    $cell->setCellValue('H1','上装信息');
    $cell->setCellValue('S1','下装信息');
    //表格基本内容
    for($i=0;$i<$cellNum;$i++){
        $cell->setCellValue($cellName[$i].'2', $expCellName[$i]);
        $cell->getStyle($cellName[$i].'2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $cell->getStyle($cellName[$i].'2')->getFont()->setBold(true);
    }

    //设置值
    foreach($expTableData as $key=>$val){
        for($k=0;$k<$cellNum;$k++){
            $cell->setCellValue($cellName[$k].($key+3),$val[$k]);
        }
    }
    ob_clean();//清除缓冲区,避免乱码：
    header('pragma:public');
    header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xlsx"');
    header("Content-Disposition:attachment;filename=$expTitle.xlsx");//attachment新窗口打印inline本窗口打印
    flush();
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('php://output');
    exit;
}
?>